package com.hankol.newretail.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.*
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import com.baselibrary.Constants
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.setMallPriceTTF
import com.baselibrary.extension.toast
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.net.APIResponse
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.hankol.newretail.ConfirmNewRetailOrderActivity
import com.hankol.newretail.R
import com.hankol.newretail.adapter.details.GoodsSpecAdapter
import com.hankol.newretail.bean.goods_details.*
import com.hankol.newretail.databinding.FragmentNormsBinding
import com.hankol.newretail.viewmodel.GoodsDetailViewModel
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.roundToInt

/**
 * @description 种草秀弹窗
 * @author 关忆北、
 * @time 2022/8/30 11:56 上午
 */
class GoodsNormsDialog : DialogFragment() {
    private var num = 1
    var normsType: Int = -1
    var goodsId: Long = 0
    var skuId: Long = 0
    private var goodsDetails: GoodsDetails? = null
    private lateinit var dataBinding: FragmentNormsBinding
    private val viewModel: GoodsDetailViewModel by lazy { GoodsDetailViewModel() }
    private var mOnCloseClickListener: OnCloseClickListener? = null
    private val mGoodsSpecAdapter: GoodsSpecAdapter by lazy { GoodsSpecAdapter() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.DialogStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_norms, null, false)
        return dataBinding.root
    }

    override fun onResume() {
        super.onResume()
        dialog?.window?.let {
            it.setGravity(Gravity.BOTTOM)
            it.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, (ScreenUtils.getScreenHeight() / 1.7f).roundToInt())
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dataBinding.rvNormsList.adapter = mGoodsSpecAdapter
        initObserve()
    }

    fun setOnCloseClickListener(listener: OnCloseClickListener) {
        this.mOnCloseClickListener = listener
    }

    fun limitRangeStr(limitRangeFix: Int): String {
        when (limitRangeFix) {
            1 -> {
                return "每日"
            }
            2 -> {
                return "每周"
            }
            3 -> {
                return "每月"
            }
        }
        return ""
    }

    private fun initObserve() {
        viewModel.reqGoodsDetails(goodsId, skuId, object : APIResponse<GoodsDetails>(this) {
            @SuppressLint("SetTextI18n")
            override fun onSuccess(result: GoodsDetails, json: String) {
                num = 1
                viewModel.nameList.clear()
                viewModel.specValueMap.clear()
                viewModel.normsIndexOf.clear()
                viewModel.specNameMap.clear()
                viewModel.specRenderList.clear()
                viewModel.specRelationMap.clear()
                viewModel.seckillSpuDetailSkuMap.clear()
                goodsDetails = result
                viewModel.analysisJson(json)
                viewModel.assembleNormsIndex(result)
                var specList: ArrayList<GoodsSpecBean> = arrayListOf()
                for (i in 0 until viewModel.nameList.size) {
                    var goodsSpecBean = GoodsSpecBean()
                    goodsSpecBean.groupName = viewModel.specNameMap[viewModel.nameList[i]].toString()
                    goodsSpecBean.groupId = viewModel.nameList[i].toLong()
                    goodsSpecBean.defaultSku = if (viewModel.defSelectedSkuList.isEmpty()) viewModel.getDefSelectedSku(result)[i] else viewModel.defSelectedSkuList[i]
                    goodsSpecBean.specRelationMap = viewModel.specRelationMap
                    var specValueList = viewModel.specRenderList[viewModel.nameList[i]]
                    var childList: ArrayList<Spec> = arrayListOf()
                    for (i in 0 until specValueList!!.size) {
                        var child = Spec(goodsSpecBean.groupName, goodsSpecBean.groupId, viewModel.specValueMap[specValueList[i]]!!, specValueList[i].toLong(), goodsSpecBean.specRelationMap.containsKey(specValueList[i]))
                        childList.add(child)
                    }
                    goodsSpecBean.specList = childList
                    specList.add(goodsSpecBean)
                }
                mGoodsSpecAdapter.setNewData(specList)


                if (result.policy.limitNum > 0) {
                    //限购情况下
                    dataBinding.tvNormsList.text = if (result.buyPolicyText.checkNotNull()) "（${result.buyPolicyText}）" else ""
                }
                initListener()
            }
        })

        viewModel.addCartShopLD.observe(this, Observer {
            if (it != null && it.success) {
                //关闭弹窗
                ToastUtils.showShort(ContextUtils.getCurApplication().applicationContext, "加入购物车成功")
                mOnCloseClickListener?.onAddCartClick(it.count)
                mOnCloseClickListener?.onCloseClick()
            }
        })
    }

    fun initListener() {

        dataBinding.llNormsReduce.setOnClickListener {
            //-1
            num -= 1
            if (num < 1) {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    "最少购买1件".toast()
                }
                num = 1
            } else {
                dataBinding.ivNormsPlus.setImageResource(R.drawable.ic_goods_add_true)
                dataBinding.ivNormsReduce.setImageResource(R.drawable.ic_goods_reduce_true)
            }
            if (num == 1) {
                dataBinding.ivNormsPlus.setImageResource(R.drawable.ic_goods_add_true)
                dataBinding.ivNormsReduce.setImageResource(R.drawable.ic_goods_reduce_false)
            }
            dataBinding.tvNormsNum.text = num.toString()
        }
        dataBinding.llNormsPlus.setOnClickListener {

            //+1
            goodsDetails?.let {
                val skuBean = viewModel.getSkuBean(mGoodsSpecAdapter)
                skuBean?.let { skuBean ->
                    var isBuyBtnStatus: Int = -1
                    val maxNum = if (skuBean.stock > it.policy.allowBuyNum) {
                        //购买数以限购为准
                        isBuyBtnStatus = 1
                        it.policy.allowBuyNum
                    } else {
                        //购买数以库存为准
                        isBuyBtnStatus = 0
                        skuBean.stock
                    }

                    if (maxNum < num + 1) {
                        if (isBuyBtnStatus == 0) {
                            if (!DoubleClickHelper.isOnDoubleClick()) {
                                "超出最大库存".toast()
                            }
                        } else {
                            if (it.policy.orderedNum > 0) {
                                if (!DoubleClickHelper.isOnDoubleClick()) {
                                    ToastUtils.showShort(requireContext(), "商品【${limitRangeStr(it.policy.limitRangeFix)}限购${it.policy.limitNum}${it.unitName}】，您已下单${it.policy.orderedNum}件")
                                }
                            } else {
                                if (!DoubleClickHelper.isOnDoubleClick()) {
                                    ToastUtils.showShort(requireContext(), "商品【${limitRangeStr(it.policy.limitRangeFix)}限购${it.policy.limitNum}${it.unitName}】")
                                }
                            }
                        }
                        dataBinding.ivNormsPlus.setImageResource(R.drawable.ic_goods_add_false)
                        return@setOnClickListener
                    }

                    num += 1
                    dataBinding.tvNormsNum.text = num.toString()
                    dataBinding.ivNormsReduce.setImageResource(R.drawable.ic_goods_reduce_true)
                    if (maxNum == num) {
                        dataBinding.ivNormsPlus.setImageResource(R.drawable.ic_goods_add_false)
                    }
                }
            }

        }
        dataBinding.ivGoodsServiceClose.setOnClickListener {
            mOnCloseClickListener?.onCloseClick()
        }
        dataBinding.tvGoodsAffirm.setOnClickListener {
            val buffer = StringBuffer()
            for (d in mGoodsSpecAdapter.data) {
                buffer.append(d.groupId).append(d.defaultSku.valueId)
            }

            if (viewModel.normsIndexOf.containsKey(buffer.toString())) {
                val skuBean = viewModel.normsIndexOf[buffer.toString()]
                if (normsType == NORMS_SHOP_GOODS) {
                    var price = if (SpUtils.getInstance().loadUserBean.data.isFans == 1) {
                        skuBean?.showFansPrice
                    } else {
                        skuBean?.showPrice
                    }
                    goodsDetails?.let {
                        var seckill_id = ""
                        var seckill_name = ""
                        it.seckillActProductExtDTO?.let {
                            seckill_id = "${it.seckillActId}"
                            seckill_name = it.seckillActName.checkValue()
                        }
                        SensorsDataManager.instance.productBuy(
                            skuBean?.id.toString(), if (it.shopInfo == null) "酣客总社" else it.shopInfo.name.checkValue(), it.name.checkValue(), buffer.toString(), AmountUtil.changeF2Y(price!!.toString()), num, if (it.seckillActProductExtDTO.checkNotNull()) "是" else "否", seckill_id, seckill_name
                        )
                    }
                    val hashMap: HashMap<String, Any> = hashMapOf()
                    hashMap[ConfirmNewRetailOrderActivity.KEY_CONFIRM_ORDER_NUM] = num
                    hashMap[ConfirmNewRetailOrderActivity.KEY_CONFIRM_ORDER_SKUID] = skuBean?.id.toString()
                    ARouterUtils.jump(ActivityRouter.NEW_RETAIL.CONFIRM_ORDER, hashMap)
                    dismiss()
                } else {
                    skuBean?.id?.let { it1 -> viewModel.reqAddCartShop(it1, num) }
                }
            } else {
                ToastUtils.showShort(ContextUtils.getCurApplication().applicationContext, "未找到规格！")
            }
        }
        dataBinding.rciNormsCover.setOnClickListener {
            val skuBean: MallSkuDto = viewModel.getSkuBean(mGoodsSpecAdapter)
                    ?: return@setOnClickListener
            val bundle = Bundle()
            val imgList: ArrayList<String> = ArrayList<String>(skuBean.covers)
            bundle.putStringArrayList(Constants.WIKI_PICTURE_LIST, imgList)
            bundle.putInt(Constants.WIKI_PICTURE_INDEX, 0)
            ActivityRouter.startActivity(ActivityRouter.ACTIVITY.BROWSE_MEDIA, bundle)
        }
        dataBinding.rciNormsCover.postDelayed({
            showGoodsInfo()
        }, 200)
        mGoodsSpecAdapter.setOnUpdateGoodsInfoCallBack(object : GoodsSpecAdapter.OnUpdateGoodsInfoCallBack {
            override fun onUpdateGoodsInfo() {
                showGoodsInfo()
            }
        })


    }

    private fun showGoodsInfo() {
        if (!mGoodsSpecAdapter.data.isNullOrEmpty()) {
            val buffer = StringBuffer()
            for (d in mGoodsSpecAdapter.data) {
                buffer.append(d.groupId).append(d.defaultSku.valueId)
            }
            if (viewModel.normsIndexOf.containsKey(buffer.toString())) {
                val skuBean = viewModel.normsIndexOf[buffer.toString()]
                skuBean?.covers?.let {
                    if (it.isNotEmpty()) {
                        mOnCloseClickListener?.onClickImgCover(it[0])
                        GlideUtils.loadImg_101(ContextUtils.getCurApplication(), it[0], dataBinding.rciNormsCover)
                    }
                }

                dataBinding.tvNormsPrice.setMallPriceTTF(ContextUtils.getCurApplication().applicationContext)
                dataBinding.tvUnit.setMallPriceTTF(ContextUtils.getCurApplication().applicationContext)

                if (viewModel.seckillSpuDetailSkuMap.isNotEmpty()) {
                    if (viewModel.seckillSpuDetailSkuMap.containsKey(skuBean?.id.toString())) {
                        dataBinding.tvNormsStock.text = "库存 ${viewModel.seckillSpuDetailSkuMap[skuBean?.id.toString()]?.stock}"
                    }
                    var startTime = goodsDetails?.seckillActProductExtDTO?.stime!!
                    var endTime = goodsDetails?.seckillActProductExtDTO?.etime!!
                    if (System.currentTimeMillis() < startTime) {
                        dataBinding.tvNormsPrice.text = if (SpUtils.getInstance().loadUserBean.data.isFans == 1) {
                            "${AmountUtil.changeF2Y(skuBean?.showFansPrice.toString())}"
                        } else {
                            "${AmountUtil.changeF2Y(skuBean?.showPrice.toString())}"
                        }
                    } else if (System.currentTimeMillis() in startTime..endTime) {
                        dataBinding.tvNormsPrice.text = if (SpUtils.getInstance().loadUserBean.data.isFans == 1) {
                            "${AmountUtil.changeF2Y(viewModel.seckillSpuDetailSkuMap[skuBean?.id.toString()]?.fansPrice.toString())}"
                        } else {
                            "${AmountUtil.changeF2Y(viewModel.seckillSpuDetailSkuMap[skuBean?.id.toString()]?.price.toString())}"
                        }
                    }
                    mOnCloseClickListener?.onClickSpec(skuBean?.showFansPrice!!, skuBean.showPrice,viewModel.seckillSpuDetailSkuMap[skuBean?.id.toString()]?.fansPrice!!.toLong(), viewModel.seckillSpuDetailSkuMap[skuBean?.id.toString()]?.price!!.toLong(), skuBean.id)
                } else {
                    dataBinding.tvNormsStock.text = "库存 ${skuBean?.stock}"
                    dataBinding.tvNormsPrice.text = if (SpUtils.getInstance().loadUserBean.data.isFans == 1) {
                        "${AmountUtil.changeF2Y(skuBean?.showFansPrice.toString())}"
                    } else {
                        "${AmountUtil.changeF2Y(skuBean?.showPrice.toString())}"
                    }
                    mOnCloseClickListener?.onClickSpec(skuBean?.showFansPrice!!, skuBean.showPrice,0L,0L, skuBean.id)
                }
                goodsDetails?.let {
                    val skuBean = viewModel.getSkuBean(mGoodsSpecAdapter)
                    skuBean?.let { skuBean ->
                        val maxNum = if (skuBean.stock > it.policy.allowBuyNum) {
                            //购买数以限购为准
                            it.policy.allowBuyNum
                        } else {
                            //购买数以库存为准
                            skuBean.stock
                        }

                        if (maxNum <= 1) {
                            dataBinding.ivNormsReduce.setImageResource(R.drawable.ic_goods_reduce_false)
                            dataBinding.ivNormsPlus.setImageResource(R.drawable.ic_goods_add_false)
                        } else if (maxNum > 1) {
                            dataBinding.ivNormsPlus.setImageResource(R.drawable.ic_goods_add_true)
                        }
                    }
                }
            }
        }
    }

    interface OnCloseClickListener {
        fun onCloseClick()
        fun onClickImgCover(url: String)
        fun onAddCartClick(num: Int)
        fun onClickSpec(fansPrice: Long, price: Long, seckillFansPrice: Long, seckillPrice: Long, skuId: Long)
    }

    companion object {
        const val NORMS_SHOP_CART: Int = 1//加入购物车
        const val NORMS_SHOP_GOODS: Int = 2//商品购买
    }

    override fun onStop() {
        super.onStop()
        val buffer = StringBuffer()
        for (d in mGoodsSpecAdapter.data) {
            buffer.append(d.groupId).append(d.defaultSku.valueId)
        }
        if (viewModel.normsIndexOf.containsKey(buffer.toString())) {
            val skuBean = viewModel.normsIndexOf[buffer.toString()]
            skuBean?.let {
                viewModel.defSelectedSkuList = it.specList
            }
        }
    }
}